package com.atgugu.flink.chapter11;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.table.descriptors.Schema;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lzc
 * @Date 2022/4/11 9:12
 */
public class Flink06_Table_kafka {
    public static void main(String[] args) {
        // 流->动态表->连续查询->动态表->流
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        // 直接把文件中的内容加载动态表中
        
        Schema schema = new Schema()
            .field("id", DataTypes.STRING())
            .field("ts", DataTypes.BIGINT())
            .field("vc", DataTypes.INT());
    
    
        tEnv
            .connect(new Kafka()
                         .version("universal")
                         .property("bootstrap.servers", "hadoop162:9092,hadoop163:9092,hadoop164:9092")
                         .property("group.id", "atguigu")
                         .topic("s1")
                         .startFromLatest()
            )
            .withFormat(new Csv())
            .withSchema(schema)
            .createTemporaryTable("sensor");
    
        Table table = tEnv.from("sensor");
        Table result = table.where($("id").isEqual("sensor_1")).select($("id"), $("ts"), $("vc"));
    
    
        tEnv
            .connect(new Kafka()
                         .version("universal")
                         .property("bootstrap.servers", "hadoop162:9092,hadoop163:9092,hadoop164:9092")
                         .topic("s2")
                         .sinkPartitionerRoundRobin()
            )
            .withFormat(new Csv().lineDelimiter(""))
            .withSchema(schema)
            .createTemporaryTable("abc");
        
        result.executeInsert("abc");  // 把result的数据插入到动态表abc中
        
        
    
    }
}
